<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <el-col v-if="userInfo.userId === '1'" :span="4" class="div-height-left">
        <sys-org-tree @treeClick="treeClick"/>
      </el-col>
      <el-col :span="userInfo.userId === '1' ? 20 : 24" :xs="24">
        <div class="search-container">
          <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams"
                   label-width="80px">
            <el-form-item label="号别名称" prop="name">
              <el-input v-model="queryParams.name" clearable placeholder="请输入号别名称"
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item class="dept-tree-label" label="归属科室" prop="deptId">
              <base-dept-tree :org-id="queryParams.orgId" :value="queryParams.deptId" style="width: 120px;"/>
            </el-form-item>
            <el-form-item label="所属医生" prop="doctorId">
              <el-select v-model="queryParams.doctorId" class="width-120" clearable filterable
                         placeholder="请选择所属医生" @change="getList">
                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName"
                           :value="item.userId"></el-option>
              </el-select>

            </el-form-item>
            <div class="mr20" style="float: right">
              <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
            </div>
          </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:clinicIndex:add']" :disabled="!queryParams.orgId" plain
                       type="primary" @click="handleAdd">
              <template #icon>
                <i-ep-plus/>
              </template>
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:clinicIndex:edit']" :disabled="single" plain type="success"
                       @click="handleUpdate">
              <template #icon>
                <i-ep-edit/>
              </template>
              修改
            </el-button>
          </el-col>
          <!--                    <el-col :span="1.5">-->
          <!--                        <el-button-->
          <!--                            v-hasPerm="['base:clinicIndex:remove']"-->
          <!--                            :disabled="multiple"-->
          <!--                            icon="el-icon-delete"-->
          <!--                            plain-->
          <!--                            -->
          <!--                            type="danger"-->
          <!--                            @click="handleDelete"-->
          <!--                        >删除-->
          <!--                        </el-button>-->
          <!--                    </el-col>-->
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:clinicIndex:export']"
                       :disabled="!queryParams.orgId && clinicIndexList.length <= 0" plain type="warning"
                       @click="handleExport">
              <template #icon>
                <i-ep-download/>
              </template>
              导出
            </el-button>
          </el-col>
        </el-row>

        <el-table v-adaptive :border="true" :data="clinicIndexList" :header-cell-style="$headerCellStyle" :stripe="true"
                  highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column :align="'center'" type="selection" width="55"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="号别名称" prop="name"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="门诊科室" prop="deptName"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="所属医生" prop="doctorName"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊疗项目"
                           prop="clinicItemName"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="排序" prop="sort"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注信息" prop="remark"/>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="280">
            <template #default="scope">
              <el-button v-hasPerm="['base:clinicIndex:edit']" type="success"
                         @click="handleUpdate(scope.row)">
                <template #icon>
                  <i-ep-edit/>
                </template>
                修改
              </el-button>
              <el-button v-hasPerm="['base:clinicIndex:remove']" type="danger"
                         @click="handleDelete(scope.row)">
                <template #icon>
                  <i-ep-delete/>
                </template>
                删除
              </el-button>
              <el-button v-hasPerm="['base:clinicIndex:scheduleArrangement']" type="success"
                         @click="scheduleArrangement(scope.row)">
                <template #icon>
                  <i-ep-first-aid-kit/>
                </template>
                出诊安排
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改号别对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="600px"
               @close="cancel">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="40">
          <el-col :span="24">
            <el-form-item label="门诊科室" prop="deptId">
              <base-dept-tree :org-id="queryParams.orgId" :value="form.deptId" style="width: 100%;"
                              @deptSelect="deptNodeClick"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="号别类型" prop="registerFlag">
              <el-select
                v-model="form.registerFlag"
                placeholder="请选择号别类型"
                style="width: 100%"
                @change="registerFlagChange"
              >
                <el-option
                  v-for="dict in dictDataMap['register_flag_dict']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="号别名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入号别名称" @input="nameInput"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="诊疗项目">
              <el-input v-if="isShow" v-model="form.clinicItemName"
                        @focus="isShowItemNameFocus()">
              </el-input>
              <automatic-completion v-else ref="itemAutomatic" :dict-array="dictArray" :table-body-list="tableBodyList"
                                    :table-head-list="tableHeadList" :title="itemTitle" style="width: 100%;"
                                    @itemNameInput="itemNameInput" @rowClick="rowClick"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属医生" prop="doctorId">
              <el-select v-model="form.doctorId" clearable filterable placeholder="请选择"
                         style="width: 100%">
                <el-option v-for="item in deptInUserList" :key="item.userId" :label="item.nickName"
                           :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="拼音码" prop="inputCode">
              <el-input v-model="form.inputCode" placeholder="请输入拼音码"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注信息">
              <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>
    <clinic-schedule ref="clinicScheduleRef"/>
  </div>
</template>

<script lang="ts" setup>
import {
  addClinicIndex,
  delClinicIndex,
  getClinicIndex,
  selectPageClinicIndex,
  updateClinicIndex
} from "@/api/base/clinicIndex";
import {listDept} from "@/api/system/dept";
import {getDeptInUserList} from '@/api/system/user'
import {firstLetterResult} from "@/utils/pinyin"
import {autoBuildQuery, getClinicItemDict, listClinicItemDict} from "@/api/base/clinicItemDict";
import clinicSchedule from "@/views/base/clinicIndex/clinicSchedule.vue";
// 项目自动补全组件
import AutomaticCompletion from "@/components/AutomaticCompletion/index.vue";
import baseDeptTree from "@/components/Dept/baseDeptTree.vue";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {clinicTableHeadList, jsonStrInObj} from "@/utils/autoComplete"

const useUserStore = useUserStoreHook();
const clinicScheduleRef = ref()
const {proxy} = getCurrentInstance() as any
const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData('bill_item_class_dict', 'register_flag_dict'))
const itemAutomatic = ref()
const formRef = ref()
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
// 选中数组
const ids = ref<any>([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 日期范围
const dateRange = ref<any>([])
// 号别表格数据
const clinicIndexList = ref<any>([])
// 科室树选项
const deptOptions = ref<any>([])
// 科室list
const listDeptList = ref<any>([])
// 相应科室下对应的用户
const deptInUserList = ref<any>([])
// 机构下所有医生信息
const userList = ref<any>([])
// 机构下所有诊疗信息
const itemAllList = ref<any>([])
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  deptId: undefined,
  doctorId: undefined,
  clinicItemId: undefined,
  sort: undefined,
  inputCode: undefined,
  orgId: undefined,
})
// 表单参数
const form = ref<any>({
  clinicItemName: '',
  clinicItemId: '',
  inputCode: '',
  itemInfo: ''
})
// 表单校验
const rules = ref({
  name: [
    {required: true, message: "号别名称不能为空", trigger: "blur"}
  ],
  deptId: [
    {required: true, message: "门诊科室不能为空", trigger: "blur"}
  ],
  clinicItemName: [
    {required: true, message: "项目名称不能为空", trigger: "change"}
  ],
  sort: [
    {required: true, message: "排序不能为空", trigger: "blur"}
  ],
  registerFlag: [
    {required: true, message: "号别类型不能为空", trigger: "change"}
  ]
})
// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(clinicTableHeadList))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict'])
let isShow = ref(true);


watch(() => form.deptId, (newValue, _oldValue) => {
  if (!newValue) {
    deptInUserList.value = []
  }
})
watch(() => queryParams.orgId, (_newValue, _oldValue) => {

})

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId
  getUserList()
  getDeptTree()
  getItemAllList()
}

/** 左侧科室树节点点击事件 */
function treeClick(obj) {
  queryParams.value.orgId = obj.id
  getDeptTree()
  getUserList()
  getItemAllList()
}

/** 查询科室下拉树结构 */
function getDeptTree() {
  let clinicVsVisitArray = ['2', '3', '4']
  listDept({
    'delFlag': '0',
    'status': '0',
    'orgId': queryParams.value.orgId,
    "clinicVsVisitArray": clinicVsVisitArray
  }).then(response => {
    listDeptList.value = response.data
    if (form.value.deptId) {
      let index = Array.from(response.data).findIndex((item: any) => {
        return item.deptId = form.value.deptId
      })
      if (index === -1) {
        form.value.deptId = undefined
      }
    }
    deptOptions.value = proxy.$handleTree(response.data, "deptId", "deptName");
  });
}

/**
 * 号别类型选择框值改变事件
 */
function registerFlagChange() {
  const index = dictDataMap.value['register_flag_dict'].findIndex((item: any) => {
    return item.dictValue === form.value.registerFlag
  })
  if (index > -1) {
    const registerFlagName = dictDataMap.value['register_flag_dict'][index].dictLabel
    const deptName = form.value.deptName ? form.value.deptName : ""
    form.value.name = deptName + registerFlagName
    form.value.registerFlagName = registerFlagName
  }
}

/** 获取相应科室下的医生 */
function getDeptInUserListFun() {
  let obj = {
    orgId: queryParams.value.orgId,
    deptId: form.value.deptId,
    status: '0',
    delFlag: '0'
  }
  getDeptInUserList(obj).then(res => {
    deptInUserList.value = res.data
  })
}

/** 获取相应科室下的医生 */
function getUserList() {
  let obj = {
    orgId: queryParams.value.orgId,
    status: '0',
    delFlag: '0'
  }
  getDeptInUserList(obj).then(res => {
    userList.value = res.data
  })
}

/** 科室树选择事件 */
function deptNodeClick(obj) {
  form.value.deptId = obj.deptId
  form.value.deptName = obj.deptName
  registerFlagChange()
  getDeptInUserListFun()
}

/** 查询号别列表 */
function getList() {
  selectPageClinicIndex(queryParams.value).then((response: any) => {
    let rows = response.rows
    rows.forEach(item => {
      // 科室翻译
      listDeptList.value.forEach(dept => {
        if (item.deptId === dept.deptId) {
          item.deptName = dept.deptName
        }
      })
      // 医生翻译
      if (item.doctorId) {
        userList.value.forEach(user => {
          if (item.doctorId === user.userId) {
            item.doctorName = user.nickName
          }
        })
      }
      // 诊疗项目

      itemAllList.value.forEach(clinicItem => {
        if (item.clinicItemId === clinicItem.clinicItemId) {
          item.clinicItemName = clinicItem.itemName
        }
      })
    })
    clinicIndexList.value = rows;
    total.value = response.total;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    clinicIndexId: undefined,
    name: undefined,
    deptId: undefined,
    doctorId: undefined,
    clinicItemId: undefined,
    sort: undefined,
    inputCode: undefined,
    orgId: queryParams.value.orgId,
    delFlag: undefined,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined,
    remark: undefined
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.clinicIndexId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加号别";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const clinicIndexId = row.clinicIndexId || ids.value
  getClinicIndex(clinicIndexId).then(response => {
    form.value = response.data;
    getDeptInUserListFun()
    getClinicItemDictFun()
    title.value = "修改号别";
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      form.value.inputCode = firstLetterResult(form.value.name)
      if (form.value.clinicIndexId != null) {
        updateClinicIndex(form.value).then(_response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
        });
      } else {
        addClinicIndex(form.value).then(_response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const clinicIndexIds = row.clinicIndexId || ids.value;
  ElMessageBox.confirm('是否确认删除号别编号为"' + clinicIndexIds + '"的数据项？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delClinicIndex(clinicIndexIds).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  // download('base/clinicIndex/export', {
  //     ...queryParams
  // }, `clinicIndex_${new Date().getTime()}.xlsx`)
}

/** 号别名称输入框改变事件 设置拼音码*/
function nameInput(value) {
  debugger
  if (value) {
    form.value.inputCode = firstLetterResult(value)
  } else {
    form.value.inputCode = ""
  }
}

/*************************************************** 自动补全 **********************************************/
/** 项目名称自动补全检索 */
function itemNameInput(itemName) {
  form.value.itemInfo = itemName
  getListClinicItemDict()
}

/** 机构下所有诊疗信息 */
function getItemAllList() {
  form.value.orgId = queryParams.value.orgId
  form.value.notInSelect = ['A', 'B', 'F', 'C', 'D', 'E', 'F', 'G', 'H']
  // 是否过滤已存在的项目标记
  form.value.isFiltrationContrastExist = false
  listClinicItemDict(form.value).then(res => {
    itemAllList.value = res.data
    getList()
  })
}

/** 自动补全后台查询 */
function getListClinicItemDict() {
  if (form.value.itemInfo) {
    form.value.notInSelect = ['A', 'B', 'F', 'C', 'D', 'E', 'F', 'G', 'H']
    // 是否过滤已存在的项目标记
    form.value.isFiltrationContrastExist = true
    autoBuildQuery(form.value).then(res => {
      tableBodyList.value = res.data
      // 打开自动补全弹出框
      itemAutomatic.value.init()
    })
  } else {
    tableBodyList.value = []
  }
}

/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
function isShowItemNameFocus() {
  isShow.value = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.clinicItemName)
    itemAutomatic.value.focusInput()
  })
}


/** 项目列表行点击事件 */
function rowClick(row) {
  itemAutomatic.value.closePopover()
  isShow.value = true
  form.value.clinicItemId = row.clinicItemId
  form.value.clinicItemName = row.itemName
  tableBodyList.value = []
}

/** 项目选择关闭事件 */
function closePopover() {
  // itemAutomatic.closePopover()
  tableBodyList.value = []
}

/** 查询诊疗项目 */
function getClinicItemDictFun() {
  getClinicItemDict(form.value.clinicItemId).then(res => {
    form.value.itemInfo = res.data.itemName
    form.value.clinicItemName = res.data.itemName
    open.value = true;
    nextTick(() => {
      itemAutomatic.value.setItemName(res.data.itemName)
    })
  })
}

/************************************************ 出诊安排 **********************************************/
/** 出诊安排 */
function scheduleArrangement(row) {
  clinicScheduleRef.value.showClinicScheduleDrawerFun(row)
}
</script>


<script lang="ts">
export default {
  name: "ClinicIndex"
}
</script>
<style scoped></style>
